#include "rcrypto.h"
#include "rnet.h"
#include "database.h"
#include "parse_task.h"
#include "read_task.h"
#include "main_service.h"

#include <jsoncpp/json/reader.h>
#include <jsoncpp/json/json.h>
using namespace	Json ;

void read_task::run()
{
	rmutex(m_task.m_lock);

	int ret = 0 ;
	bool b_close = false ;
	
	rlog << "read(" << m_task.mi_fd << ")" << endl ;
	while ( true )
	{
		char buffer[SOCKET_BUFFER_SIZE] = { 0x00 } ;
		ret = ::read( m_task.mi_fd, buffer, SOCKET_BUFFER_SIZE ) ;
		if( ret < 0 )
		{
			if( errno == EINTR )
				continue ;

			if ( errno == EAGAIN )
				break;

			rlog << "read(" << m_task.mi_fd << ") error : " << strerror( errno ) << endl;
			b_close = true ;
			break ;
		}

		if ( ret == 0 )
		{
			rlog << "read(" << m_task.mi_fd << ") peer closed" << endl ;
			b_close = true ;
			break ;
		}

		copy( buffer, buffer+ret, back_inserter( m_task.mv_data ) ) ;
	}

	while(true)
	{
		if ( (int)m_task.mv_data.size() < 4 )
		{
			if ( b_close )
				goto quit;

			return ;
		}

		int length = 0 ;
		memcpy( (char*)&length, &m_task.mv_data[0], 4 ) ;

		if ( (int)m_task.mv_data.size() < length + 4 )
		{
			if ( b_close )
				goto quit;

			return;
		}

		string s_json(m_task.mv_data.begin()+4, m_task.mv_data.begin()+4+length) ;
		m_task.m_time = time(NULL) ;	
		m_task.mv_data.erase(m_task.mv_data.begin(), m_task.mv_data.begin()+4+length) ;

		rlog << "read main(" << m_task.mi_fd << ") data " << endl << s_json << endl ;	

		rthreadpool::_instance().add_task(new parse_task(m_task, s_json)) ;
	}
	
quit:
	main_service::_instance().delete_task(m_task);
}

